//
//  SDHttpServerManager.m
//  SBooks
//
//  Created by shansander on 2016/11/23.
//  Copyright © 2016年 shansander. All rights reserved.
//

#import "SDHttpServerManager.h"
#import "HTTPServer.h"

#import "DDLog.h"

#import "DDTTYLogger.h"

#import "MyHTTPConnection.h"
#import "Reachability.h"
NSInteger const http_port = 4000;

@implementation SDHttpServerManager
{
    HTTPServer * _httpServer;
}

+ (SDHttpServerManager *)getHttpServer
{
    static SDHttpServerManager * server = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        server = [[SDHttpServerManager alloc] init];
    });
    return server;
}
- (id)init
{
    self = [super init];
    if (self) {
        [self configServer];
    }
    return self;
}

- (void)configServer
{
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    _httpServer = [[HTTPServer alloc] init];
    
    [_httpServer setType:@"_http._tcp."];
    
    [_httpServer setPort:http_port];
    
    NSString * docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"web"] stringByDeletingLastPathComponent];
    
    
    NSLog(@"Setting document root: %@",docRoot);
    
    
    [_httpServer setDocumentRoot:docRoot];
    
    [_httpServer setConnectionClass:[MyHTTPConnection class]];
}

- (void)startServerFinish:(void(^)(HTTPServer * hs))finish error:(void(^)(void))errorFinish{
    NSError * error;
    if (![_httpServer start:&error]) {
        errorFinish();
    }else{
        finish(_httpServer);
    }
}

- (void)stopServer
{
    [_httpServer stop];
}

- (BOOL)GetCurntNet
{
    Reachability * reach = [Reachability reachabilityForLocalWiFi];
   return [reach isReachableViaWiFi];
}




@end
